/*
 * @Description: 验证jwt令牌服务
 * @Author: lihk
 * @Date: 2024-10-08 17:16:58
 */
import { Injectable } from '@nestjs/common';
import * as jwt from 'jsonwebtoken';
import { jwtConstants } from 'src/utils/constants';

@Injectable()
export class JwtService {
  constructor() {}
  generateToken(payload: any): string {
    const secret = jwtConstants.secret;
    const expiresIn = jwtConstants.expiresIn; // 令牌有效期，例如 '3600s', '24h', '7d'
    console.log("🚀 ~ JwtService ~ generateToken ~ expiresIn:", expiresIn)
    return jwt.sign(payload, secret, { expiresIn });
  }
  verifyToken(token: string): any {
    const secret = jwtConstants.secret; // 从环境变量中获取秘钥
    try {
      const decoded = jwt.verify(token, secret);
      console.log("🚀 ~ JwtService ~ verifyToken ~ decoded:", decoded)
      return decoded;
    } catch (error) {
      console.log("🚀 ~ JwtService ~ verifyToken ~ error:", error)
      return null // 如果令牌无效，返回null
    }
  }
}